import cv2 as cv  
import numpy as np  
import matplotlib.pyplot as plt  
  
# 加载图片  
img = cv.imread("hanzi1.jpg", 0) 
  
# 如果没有图片，则程序会抛出错误  
if img is None:  
    print("Error: Unable to load image.")  
    exit()  
  
fig, ax = plt.subplots(1, 7, figsize=(15, 8))  
  
# 显示原图  
ax[0].imshow(img, cmap='gray')  
ax[0].set_title("Original Image")  
ax[0].axis('off')  
  
# 全局阈值处理 >> 二值化图  
thresh_hold, new_img = cv.threshold(img, 0, 255, cv.THRESH_BINARY + cv.THRESH_OTSU)  
inverted_img = cv.bitwise_not(new_img)    
ax[1].imshow(inverted_img, cmap='gray')  
ax[1].set_title("Inverted Image")  
ax[1].axis('off')  
  
# 应用腐蚀操作 >> 去除噪点  
kernel = np.ones((3, 3), np.uint8)  
eroded_img = cv.erode(inverted_img, kernel, iterations=1)   
ax[2].imshow(eroded_img, cmap='gray')  
ax[2].set_title("Eroded Image")  
ax[2].axis('off')  
  
# 应用膨胀操作 >> 突出图像特征 >> 中值滤波去除小白点  
dilated_img = cv.dilate(eroded_img, kernel, iterations=1)    
median_filtered_img = cv.medianBlur(dilated_img, 5)  
ax[3].imshow(median_filtered_img, cmap='gray')  
ax[3].set_title("Median Filtered")  
ax[3].axis('off')  
  
# 应用闭运算 >> 填充闭合区域   
kernel = np.ones((5, 5), np.uint8)   
closed_img = cv.morphologyEx(median_filtered_img, cv.MORPH_CLOSE, kernel)  
ax[4].imshow(closed_img, cmap='gray')  
ax[4].set_title("Closed Image")  
ax[4].axis('off')  
  
# Canney边缘检测  
edges = cv.Canny(closed_img, 50, 150)  
ax[5].imshow(edges, cmap='gray')  
ax[5].set_title("Canny Edge Detection")   
ax[5].axis('off')  
  
# 识别结果  
contours, _ = cv.findContours(edges, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE) 
img_copy = img.copy()  
for c in contours:  
    perimeter = cv.arcLength(c, True)  
    x, y, w, h = cv.boundingRect(c)  
    cv.rectangle(img_copy, (x, y), (x + w, y + h), (0, 255, 0), 2)  
    if perimeter > 100:    
        cv.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)  
ax[6].imshow(img_copy, cmap='gray')  
ax[6].set_title("OCR Result")   
ax[6].axis('off')  
  
plt.tight_layout()  
plt.show()